/**
 * Copyright (C) 2010 Cloudfarming <info@cloudfarming.nl>
 *
 * Licensed under the Eclipse Public License - v 1.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.eclipse.org/legal/epl-v10.html
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package nl.cloudfarming.client.planning.tactical.wizard.spray;

import java.text.NumberFormat;
import java.text.ParsePosition;
import java.util.Locale;
import nl.cloudfarming.client.planning.tactical.TacticalPlanningModule;
import org.netbeans.validation.api.Problems;
import org.netbeans.validation.api.Validator;
import org.openide.util.NbBundle;

/**
 * Class to validate a number. This is a substitute for org.netbeans.validation.api.builtin.stringvalidation.IsANumberValidator. The reason for this aproach is
 * that we can't replace the message which IsANUmberValidator generates.
 * If in the future custom message is supported bin this class and replace with builtin!!
 * @author Merijn Zengers
 */
final class NumberValidator implements Validator<String> {

    private Locale locale;
    private final String INVALID_NUMBER_MESSAGE = NbBundle.getMessage(TacticalPlanningModule.class, "field_plan.wizard.spray.planning_visual_panel_crop_protection_edit_properties.validation.invalid_number_message");

    /**
     * new NumberValidator whith default Locale
     */
    NumberValidator() {
        this(null);
    }

    /**
     * NumberValidator with Local l
     * @param l Locale
     */
    NumberValidator(Locale l) {
        this.locale = l;
    }

    
    /**
     * Validates the param model. Checks if it is a number according to the Locale
     * @param problems the problems already in place
     * @param compName componentName. Not used in this implementation
     * @param model the string which needs to be validated
     * @return return true if there are no new problems returns false if there are
     */
    @Override
    public boolean validate(Problems problems, String compName, String model) {
        ParsePosition p = new ParsePosition(0);
        NumberFormat.getNumberInstance(locale == null ? Locale.getDefault()
                : locale).parse(model, p);
        if (model.length() != p.getIndex() || p.getErrorIndex() != -1) {
            try {
                Double.valueOf(model);
                if (model.length() != model.trim().length()) {
                    throw new NumberFormatException();
                }
            } catch (NumberFormatException e) {
                problems.add(INVALID_NUMBER_MESSAGE);
                return false;
            }
        }
    return true;
    }
}
